#pragma Once
#include <unistd.h>
#include <signal.h>
#include <functional>
#include "Socket.hpp"
#include "Log.hpp"

extern Log lg;

using func_t = std::function<std::string(std::string &package)>; // 回调函数
                                                                 // 传 ServerCal.hpp类中的 Calulator函数

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        : port_(port), callback_(callback)
    {
    }

    // 服务器初始化 TCP协议
    void InitServer()
    {
        listenfd_.Socket();
        listenfd_.Bind(port_);
        listenfd_.Listen();
        lg(Info, " InitServer done errno:%d ,%s", errno, strerror(errno));
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            // 连接客户端
            std::string clientip;
            uint16_t clientport;
            int sockfd = listenfd_.Accept(&clientip, &clientport);
            if (sockfd < 0)
            {
                lg(Warning, "accept errno:&d ,%s", errno, strerror(errno));
                continue;
            }
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);

            if (fork() == 0) // 子进程来执行任务
            {
                listenfd_.Close(); // 子进程关闭 listenfd
                std::string inbuffer_stream;

                while (true)
                {
                    char inbuff[128];
                    ssize_t n = read(sockfd, inbuff, sizeof(inbuff));
                    if (n > 0)
                    {
                        inbuff[n] = 0;
                        inbuffer_stream += inbuff;
                        lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                        // 将读到的数据 写入到客户端中 ， 直到缓存区的数据读取完。
                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream); // "len\n"result exitcode
                            if (info.empty())
                                break;
                            lg(Debug, "debug, response:\n%s", info.c_str());
                            lg(Debug, "debug  剩余数据:\n%s", inbuffer_stream.c_str());
                            ssize_t w = write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n <= 0)
                        break;
                }

                exit(0); // 执行完任务的子进程退出
            }

            // 父进程 -----
            close(sockfd);
        }
    }

private:
    Sock listenfd_;
    uint16_t port_;
    func_t callback_; // 回调函数
};